package com.czz.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czz.common.exception.CustomerException;
import com.czz.manage.client.OssClient;
import com.czz.manage.client.VodClient;
import com.czz.manage.entity.Chapter;
import com.czz.manage.entity.Course;
import com.czz.manage.entity.CourseDescription;
import com.czz.manage.entity.Period;
import com.czz.manage.mapper.ChapterMapper;
import com.czz.manage.mapper.CourseDescriptionMapper;
import com.czz.manage.mapper.CourseMapper;
import com.czz.manage.mapper.PeriodMapper;
import com.czz.manage.query.AdminCourseQuery;
import com.czz.manage.query.TeacherCourseQuery;
import com.czz.manage.service.CourseService;
import com.czz.manage.vo.CourseInfoVo;
import com.czz.manage.vo.CoursePublishVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: CourseServiceImpl
 * @Author Czz
 * @Date 2020/1/19
 * @Time 20:29
 **/
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    CourseDescriptionMapper courseDescriptionMapper;

    @Autowired
    PeriodMapper periodMapper;

    @Autowired
    ChapterMapper chapterMapper;

    @Autowired
    OssClient ossClient;

    @Autowired
    VodClient vodClient;

    @Override
    @Transactional
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //保存课程基本信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo, course);
        courseMapper.insert(course);

        //保存课程详细信息
        CourseDescription description = new CourseDescription();
        description.setDescription(courseInfoVo.getDescription());
        description.setCourseId(course.getCourseId());
        courseDescriptionMapper.insert(description);

        return course.getCourseId();
    }

    @Override
    @Transactional
    public CourseInfoVo getCourseInfoById(String id) {
        //获取课程信息
        Course course = courseMapper.selectById(id);
        if (ObjectUtils.isEmpty(course)){
            throw new CustomerException(21009,"没有找到资源");
        }

        //获取课程描述信息
        QueryWrapper<CourseDescription> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",id);
        CourseDescription description = courseDescriptionMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(description)){
            throw new CustomerException(21009,"没有找到资源");
        }

        //构建Vo对象
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(course, courseInfoVo);
        BeanUtils.copyProperties(description,courseInfoVo);

        return courseInfoVo;
    }

    @Override
    @Transactional
    public void updateCourseInfoById(CourseInfoVo courseInfoVo) {

        String OSS_URL = "http://czz-education.oss-cn-shenzhen.aliyuncs.com/";

        //更新课程信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo, course);
        Course temp = courseMapper.selectById(courseInfoVo.getCourseId());
        courseMapper.updateById(course);

        //如果课程封面更新，则删除oss中图片
        if (!temp.getCover().equals(course.getCover())){
            String cover = temp.getCover().replace(OSS_URL,"").replaceAll("/","&&");
            ossClient.deleteOssFile(cover);
        }

        //更新课程描述信息
        CourseDescription description = new CourseDescription();
        description.setCourseId(courseInfoVo.getCourseId());
        description.setDescription(courseInfoVo.getDescription());
        UpdateWrapper<CourseDescription> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("course_id",courseInfoVo.getCourseId());
        courseDescriptionMapper.update(description,updateWrapper);
    }

    @Override
    public void getTeacherCoursePageList(Page<Course> pageParam, String teacherId, TeacherCourseQuery teacherCourseQuery) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_create");
        queryWrapper.eq("teacher_id", teacherId);

        if (ObjectUtils.isEmpty(teacherCourseQuery)){
            courseMapper.selectPage(pageParam,queryWrapper);
            return;
        }

        String name = teacherCourseQuery.getName();
        String categoryParentId = teacherCourseQuery.getCategoryParentId();
        String categoryId = teacherCourseQuery.getCategoryId();
        Integer level = teacherCourseQuery.getLevel();
        Integer status = teacherCourseQuery.getStatus();

        if (!StringUtils.isEmpty(name)){
            queryWrapper.like("course_name",name);
        }

        if (!StringUtils.isEmpty(categoryParentId)){
            queryWrapper.eq("category_parent_id",categoryParentId);
        }

        if (!StringUtils.isEmpty(categoryId)){
            queryWrapper.eq("category_id",categoryId);
        }

        if (!StringUtils.isEmpty(level)){
            queryWrapper.eq("course_level",level);
        }

        if (!StringUtils.isEmpty(status)){
            queryWrapper.eq("course_status",status);
        }

        courseMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    @Transactional
    public void deleteCourseById(String id) {

        String OSS_URL = "http://czz-education.oss-cn-shenzhen.aliyuncs.com/";

        //文档地址列表
        List<String> urls = new ArrayList<>();

        //视频id列表
        List<String> videoList = new ArrayList<>();

        //删除课程课时 period
        QueryWrapper<Period> periodQueryWrapper = new QueryWrapper<>();
        periodQueryWrapper.eq("course_id",id);

        List<Period> periodList = periodMapper.selectList(periodQueryWrapper);

        //遍历获取课时文档地址和视频id
        for (int i = 0; i<periodList.size(); i++){
            Period period = periodList.get(i);
            if (period.getDoc() == 1){
                String url = period.getDocUrl().replace(OSS_URL,"").replaceAll("/","&&");
                urls.add(url);
            }
            if (period.getVideo() == 1){
                String videoId = period.getVideoId();
                videoList.add(videoId);
            }
        }

        //删除数据中课时信息
        periodMapper.delete(periodQueryWrapper);

        //批量删除oss中文档
        ossClient.deleteOssFileBatch(urls);

        //批量删除视频点播中视频
        vodClient.deleteVodBatch(videoList);


        //删除课程章节 chapter
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", id);
        chapterMapper.delete(chapterQueryWrapper);

        //删除课程描述 description
        QueryWrapper<CourseDescription> descriptionQueryWrapper = new QueryWrapper<>();
        descriptionQueryWrapper.eq("course_id", id);
        courseDescriptionMapper.delete(descriptionQueryWrapper);

        //删除课程 course
        courseMapper.deleteById(id);
    }

    @Override
    public CoursePublishVo getCoursePublishById(String courseId) {
        return courseMapper.getCoursePublishVoById(courseId);
    }

    @Override
    public void publishCourseById(String courseId, Integer status) {
        Course course = new Course();
        course.setCourseId(courseId);
        course.setStatus(status);
        courseMapper.updateById(course);
    }

    @Override
    public List<Course> getAdminCoursePageList(Page<Course> pageParam, AdminCourseQuery courseQuery) {
        return courseMapper.getAdminCoursePageList(pageParam,courseQuery);
    }

    @Override
    public void updateCourseStatus(String id, Integer status) {
        Course course = new Course();
        course.setCourseId(id).setStatus(status);
        courseMapper.updateById(course);
    }

    @Override
    public List<Map<String, String>> getCourseByLikeName(String name) {
        List<Map<String, String>> mapList = new ArrayList<>();

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("course_name",name);
        List<Course> courseList = courseMapper.selectList(queryWrapper);

        courseList.forEach(course -> {
            Map<String,String> temp = new HashMap<>();
            temp.put("courseId",course.getCourseId());
            temp.put("courseName",course.getName());
            mapList.add(temp);
        });

        return mapList;
    }
}
